package com.wn.fileuporload;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Controller
public class fileUpdate {
    @RequestMapping("/upload")
    public String uploadFile(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam("discription") String discription, @RequestParam("multipartFile") MultipartFile multipartFile, Model model) throws IOException {
        //可以使用 七牛云替代下列方案 演示一下debug的牛逼用法
        //上传文件的路径
        String realPath = request.getServletContext().getRealPath("/images/");
        //上传的文件名
        String fileName = multipartFile.getOriginalFilename();
        //new File
        File file = new File(realPath,fileName);
        //判断一下我需要images文件夹是否存在 如果不存在则先创建这个文件夹
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        //把文件转移复制过去
        multipartFile.transferTo(new File(realPath+File.separator + fileName));
        model.addAttribute("msg","插入成功路径为"+new File(realPath+File.separator + fileName));
        return "/WEB-INF/success.jsp";
    }
}
